﻿using CommonLib.Base;
using CommonLib.CodeEntity;

namespace PostgreSQL.Convert;

public class FunctionConvert(FunctionCodeEntity func) : BaseConvert
{

    private readonly FunctionCodeEntity Func = func;

    protected override List<string> Run()
    {
        var pams = string.Join(",", Func.Params.Select(s => s.SqlLine()));
        var list = new List<string>();
        if (Func.Return != null)
        {
            list.Add($"CREATE OR FUNCTION {Func.Name}({pams})");
            list.Add($"RETURN {Func.Return} AS $$");
        }
        else
        {
            list.Add($"CREATE OR PROCEDURE {Func.Name}({pams})");
            list.Add($"AS $$");
        }
        if (Func.Declare != null)
        {
            list.Add("DECLARE");
            Func.Declare.ForEach(s => list.Add(s.SqlLine()));
        }
        Func.Body.ForEach(s => list.AddRange(s.SqlList()));
        return list;
    }
}
